#!/usr/bin/python
# some documentation on naming and stuff at bottom of file

# TDOD -- set up and test MySQLdb
# TODO -- change destination to point to right spot on server
# TODO -- cron job
# TODO -- get different X&Y sizes then resize to 800x600
# TODO -- switch from import os/os.system to import subprocess/subprocess.call

import os
from datetime import datetime

debug = False

if not debug:
    import MySQLdb as mdb
    con = mdb.connect('localhost','cmat','coolbeans','cmat21')
    cur = con.cursor()

xsize = 800              # Number of x pixels
ysize = 600              # Number of y pixels
headercolor = "white"
bgcolor = "black"        # Background
pointsize = 36           # Font size in pixels
fillcolor = "tan1"      # Font is filled in this color
fillcolor2 = "lightblue"      # Font is filled in this color on odd rows
strokecolor = "white"    # Font border is this color

xoffset = 0.03*xsize
yoffset = 0.1*ysize
xlabelsize = 0.05*xsize  # Tune this so words and labels don't overlap

Nevents = 5
Nrows = 9

eventx = [xlabelsize+xoffset+n*(xsize-xlabelsize-xoffset)/Nevents for n in range(Nevents)]
eventy = [yoffset+(n+1)*(ysize-2*yoffset)/Nrows for n in range(Nrows)]

dt = datetime.now()
update_draw_cmd = """-fill %s -draw 'text %d,%d "%s"' """ % \
    (headercolor,xoffset, yoffset, dt.strftime("Ring                     Last Updated at %I:%M %p"))

ring_names = ["%d:" % (x+1) for x in range(8)]
ring_draw_cmds = []
for i,ring in enumerate(ring_names):
    fill = fillcolor2 if i%2 else fillcolor
    cmd = """-fill %s -draw 'text %d,%d "%s"' """ % (fill, xoffset, eventy[i], ring)
    ring_draw_cmds.append(cmd)

text = 'Updates at http://cmat.ucmap.org/scores'
cmd = """-fill %s -draw 'text %d,%d "%s"' """ % ('white', xoffset, eventy[i+1], text)
ring_draw_cmds.append(cmd)

def get_ring_events(ring_number):
    cur.execute(\
"""SELECT level_chr,gender_chr,age_group_chr,event_type_num
FROM events
WHERE ring_id=%d AND end_timestamp IS NULL AND start_timestamp IS NULL
ORDER BY ring_order ASC;""" % ring_number)
    rows = cur.fetchall()
    return [''.join(map(str,x)) for x in rows[0:Nevents]]

def get_ring_events_debug(ring_number):
    tmp = {1:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           2:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           3:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           4:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           5:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           6:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           7:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           8:['AMA100','BMA100','CMA100','DMA100','EMA100','FMA100','GMA100'],
           }
    return tmp[ring_number][0:Nevents]

def get_ring_draw_cmds(ring_number):
    if debug:
        events = get_ring_events_debug(ring_number)
    else:
        events = get_ring_events(ring_number)
    return [""" -draw 'text %d,%d "%s"' """ % \
        (eventx[i],eventy[ring_number-1],x) for i,x in enumerate(events)]

def imagic_system_call(drawcmds,filename):
    wrapper_string = \
        "convert -size %dx%d xc:%s -pointsize %d -fill %s -stroke %s %s %s" % \
        (xsize,ysize,bgcolor,pointsize,fillcolor,strokecolor,drawcmds,filename)
    print wrapper_string
    print ''
    print eventx
    print eventy
    os.system(wrapper_string)

if __name__ == "__main__":
    drawcmds = ''.join(ring_draw_cmds) + update_draw_cmd
    for i in range(8):
        if i%2:
            drawcmds = drawcmds + " -fill %s " % fillcolor2
        else:
            drawcmds = drawcmds + " -fill %s " % fillcolor
        drawcmds = drawcmds + ''.join(get_ring_draw_cmds(i+1))
    imagic_system_call(drawcmds,'test.jpg')


# Note that the XY origin is in upper left, as in Imagemagick

##############################################################
#
#  ------------------------------------------------------------
# |   *1
# |
# | *2 Ring 1:  *3 AMA100 *4
# |
#
# *1 = xoffset from top to first text - also on bottom
# *2 = xoffset from left to first text - also on bottom
# *3 = labelsize from xoffset to end of Ring N: label
# *4 = xeventwidth measured from label across each event
